import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.text.JTextComponent;

import java.sql.*;

/**
 * Creates the menu to display ticket items, send those orders to the database,
 * and retrieve from the database for servers and hostess
 */
public class OrderWindow extends JPanel {

	private JPanel mainPanel;
	private JPanel leftPanel;
	private JPanel centerPanel;
	private JPanel bottomPanel;
	private JPanel nameBar;
	private JPanel leftMenu;
	public static ArrayList<Integer> section;

	private JLabel nameTime;

	int xSize;
	int ySize;
	int customers;
	static int pass;

	// initialize colors to be used
	final static Color newTeal = new Color(0, 153, 153);
	final static Color newYellow = new Color(255, 204, 0);
	final static Color newBlue = new Color(4, 40, 220);

	private boolean subMenu = false;
	private ArrayList<JButton> menuButton;

	private String[] menuTypes;

	private static int userID;
	private static int userJobCode;
	private static String userName;
	private static int tableNumber;

	/**
	 * Constructor for the OrderWindow class
	 * 
	 * @param id
	 *            - the userID
	 * @param jc
	 *            - job code of the user in the database
	 * @param n
	 *            - the name of the user
	 * @param c
	 *            - the number of customers at a table
	 */
	public OrderWindow(int id, int jc, String n, int c) {
		userID = id;
		userJobCode = jc;
		userName = n;
		customers = c;
		tableNumber = GUI.getTableNumber();

		// Get menu item names from the database
		
		Connection con = null;
		ResultSet menuResultSet;
		try {
			con = SqliteHelper.getConn();
			Statement menuSelectStatement = con.createStatement();
			String menuSelectQuery = "SELECT DISTINCT Specific_Cat From Menu;";
			ArrayList<String> menuArrayList = new ArrayList<>();
			menuResultSet = menuSelectStatement.executeQuery(menuSelectQuery);
			while (menuResultSet.next()) {
				menuArrayList.add(menuResultSet.getString("Specific_Cat"));
			}
			menuTypes = new String[menuArrayList.size()];
			for (int i = 0; i < menuTypes.length; i++) {
				menuTypes[i] = menuArrayList.get(i);
			}
		} catch (Exception ex) {
			System.err
					.println("Database Call Failure in OrderWindow Constructor.");
			System.err
					.println(ex.getClass().getName() + ": " + ex.getMessage());
		}
		// End of database menu load

		// call methods to set up GUI
		setWindowSize();
		initializePanels();

		buildBottomOrderPanel();
		buildOrderPanel();
		buildTicketPanel();

		mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
		mainPanel.add(leftPanel, BorderLayout.LINE_START);
		mainPanel.add(centerPanel, BorderLayout.CENTER);

		add(mainPanel);

	}// End Constructor

	/**
	 * Creates an instance of the TicketGrid class and adds to the center panel
	 */
	private void buildTicketPanel() {
		TicketGrid tg = new TicketGrid(customers);
		centerPanel.add(tg);
	}// End buildTicketPanel method

	/**
	 * Creates the leftPanel with the name/date and menu items to select
	 */
	private void buildOrderPanel() {
		buildNameBar();
		buildMenu();

		leftPanel.add(nameBar, BorderLayout.PAGE_START);
		leftPanel.add(leftMenu);
	}// End buildOrderPanel method

	/**
	 * Creates the grid pattern of menu items to be placed onto orders
	 */
	private void buildMenu() {
		leftMenu = new JPanel();
		leftMenu.setLayout(new GridLayout(3, 3));
		menuButton = new ArrayList<JButton>();
		int stop = 9; // when to stop the for loop to set up the grid if there
						// are leff than nine categories
		if (menuTypes.length < 9) {
			stop = 9;
		} else {
			stop = menuTypes.length;
		}

		for (int i = 0; i < stop; i++) {
			JButton mItem = new JButton();
			if (i > menuTypes.length - 1) {
				mItem = createMenuButton("");
			} else {
				mItem = createMenuButton(menuTypes[i]);
			}
			menuButton.add(mItem);
			leftMenu.add(mItem);
		}

		leftMenu.setSize(500, 500);
	}// End buildMenu method

	/**
	 * Creates the menu buttons to be placed on the leftMenu panel
	 * 
	 * @param label
	 *            - the name of the button
	 * @return JButton menuItem - the button to be placed on the leftMenu panel
	 */
	private JButton createMenuButton(String label) {
		JButton menuItem = new JButton(label);
		menuItem.setFont(new Font("Arial", Font.PLAIN, 30));
		menuItem.setPreferredSize(menuItem.getMinimumSize());
		menuItem.addMouseListener(new MouseListener() {

			@Override
			public void mouseClicked(MouseEvent e) {
				JButton jb = (JButton) e.getSource();
				if (subMenu == false && !jb.getText().equals("")) {
					String category = jb.getText();

					// Sets the text for each button to be a menu category
					for (int i = 0; i < menuButton.size() - 1; i++) {
						menuButton.get(i).setText("");
					}
					ArrayList<String> menuList = SqliteHelper
							.GetMenuItemsByCategory(category);
					for (int i = 0; i < menuList.size(); i++) {
						menuButton.get(i).setText(menuList.get(i));
					}

					menuButton.get(menuButton.size() - 1).setText("Categories");
					menuButton.get(menuButton.size() - 1).setBackground(
							newYellow);
					setSubMenu(true);

				} else if (subMenu == true
						&& !jb.getText().equals("Categories")) {
					// Checks to ensure that a seat has been selected then
					// passes
					// the item to set the Ticket Order
					if (TicketGrid.getIsHeaderClicked() == true
							&& TicketGrid.getArrayJB()
									.get(TicketGrid.getSeatNumber())
									.getBackground() == Color.YELLOW) {

						String itemType = jb.getText();

						/********* Makes database call here ***********/
						// Sends the itemType to the database
						// Datebase returns the type and price of the button
						// that is clicked

						TicketGrid.setTicketOrder(itemType);
					}
				} else if (subMenu == true && jb.getText().equals("Categories")) {
					// rests the buttons back to categories
					for (int i = 0; i < menuButton.size(); i++) {
						if (i < menuTypes.length) {
							menuButton.get(i).setText(menuTypes[i]);
						} else {
							menuButton.get(i).setText("");
						}
					}
					menuButton.get(menuButton.size() - 1).setBackground(
							new JButton().getBackground());
					setSubMenu(false);
				} else {
					// do nothing
				}
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

		});
		return menuItem;
	}// End createMenuButton method

	/**
	 * Sets whether the sub menu is visible or not
	 * 
	 * @param b
	 *            - true or false
	 */
	private void setSubMenu(boolean b) {
		subMenu = b;

	}// End setSubMenu method

	/**
	 * Builds a Panel that displays the username and time
	 */
	private void buildNameBar() {
		nameBar = new JPanel();
		nameBar.setLayout(new GridLayout(1, 1));
		nameBar.setPreferredSize(new Dimension(500, 150));
		nameBar.setMinimumSize(new Dimension(500, 150));

		nameTime = buildNameTime(userName, new Date());
		nameBar.add(nameTime);
		leftPanel.add(nameBar);
	}// End buildNameBar method

	/**
	 * Create a button that displays the user's name and time
	 * 
	 * @param name
	 *            - the user's name
	 * @param time
	 *            - the current time
	 * @return JButton - the button (unselectable) that contains the user's name
	 *         and time
	 */
	private JLabel buildNameTime(String name, Date time) {
		JLabel userInfo = new JLabel();
		userInfo.setHorizontalAlignment(SwingConstants.CENTER);
		DateFormat dateFormat = new SimpleDateFormat("HH:mm");
		userInfo.setText("<html>" + name + "<br />" + dateFormat.format(time)
				+ "</html>");
		userInfo.setFont(new Font("Arial", Font.PLAIN, 40));

		return userInfo;
	}// End buildNameTime method

	/**
	 * Creates two buttons (Send and Exit) and (Cancel) that reside at the
	 * bottom of the Order Window
	 */
	private void buildBottomOrderPanel() {
		JPanel sendOrder = new JPanel();
		sendOrder.setLayout(new FlowLayout());
		sendOrder.setBackground(GUI.newTeal);

		JButton sendButton = new JButton("Send and Exit");
		sendButton.setFont(new Font("Arial", Font.PLAIN, 40));
		sendButton.setPreferredSize(new Dimension(600, 75));
		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int temp = TicketGrid.custNum;
				String[] orders = new String[temp];
				int count = 1;
				for (int i = 0; i < temp; i++) {
					orders[i] = TicketGrid.arrayTA.get(i).getText();
					// orders[i]=((JTextComponent) ((Container)
					// GUI.mainPanel.getComponent(i)).getComponent(i)).getText();
					JOptionPane.showMessageDialog(null, "To Kitchen: \n"
							+ orders[i]);
					// count+=2;

					/******
					 * THIS NEEDS TO ITERATE THROUGH THE Jtext ARRAY AND INSERT
					 * IN A LOOP FOR EVERY ITEM IN EVERY SEAT USING SqliteHelper.InsertOrder()
					 *****/
					TicketGrid.sendTicketToKitchen(TicketGrid.getSeatNumber()); // Not
																				// implemented
																				// yet, just clears array.

				}

				TicketGrid.setIsHeaderClicked(-1);// reset all headers to false
				newGUIWindow();
			}
		});// End ActionListener

		JButton closeButton = new JButton("Close Tickets");
		closeButton.setFont(new Font("Arial", Font.PLAIN, 40));
		closeButton.setPreferredSize(new Dimension(600, 75));
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int temp = TicketGrid.custNum;
				String[] orders = new String[temp];
				for (int i = 0; i < temp; i++) {
					orders[i] = TicketGrid.arrayTA.get(i).getText();
					JOptionPane.showMessageDialog(null, "To Customer: \n"
							+ orders[i]);
					/********* CODE TO DELETE TICKET FROM DATABASE HERE **********/
					TicketGrid.closeTicket(TicketGrid.getSeatNumber()); // Not
																		// implemented
																		// yet
				}

				TicketGrid.setIsHeaderClicked(-1);// reset all headers to false
				newGUIWindow();
			}
		});// End ActionListener

		sendOrder.add(closeButton);

		sendOrder.add(sendButton);

		JButton cancelButton = new JButton("Cancel");
		cancelButton.setFont(new Font("Arial", Font.PLAIN, 40));
		cancelButton.setPreferredSize(new Dimension(600, 75));
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				newGUIWindow();
			}
		});// End ActionListener

		sendOrder.add(cancelButton);
		bottomPanel.add(sendOrder);
	}

	// End of buildBottomOrderPanel

	/**
	 * Creates a new instance of the GUI Class, removes the current mainPanel
	 * and replaces it with gui (GUI Class) and then validates and repaints the
	 * screen
	 */
	public void newGUIWindow() {
		if (userJobCode == 1) {
			GUI gui = new GUI(userID, userJobCode, userName);
			StartSystem.switchPanel(gui);
		} else {
			section.clear();
			GUI gui = new GUI(userID, userJobCode, userName);
			StartSystem.switchPanel(gui);
		}
	}// End newGUIWindow method

	/**
	 * Initializes the panels to be placed on Main Panel
	 */
	private void initializePanels() {
		leftPanel = new JPanel();
		leftPanel.setLayout(new BorderLayout());

		centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());

		bottomPanel = new JPanel();
		bottomPanel.setLayout(new FlowLayout());
		bottomPanel.setBackground(GUI.newTeal);

	}// End initializePanels method

	/**
	 * Sets up the size of the window to take up the entire screen. Main Panel
	 * is the container for the reminder of the class.
	 */
	private void setWindowSize() {
		Toolkit tk = Toolkit.getDefaultToolkit();
		xSize = ((int) tk.getScreenSize().getWidth());
		ySize = ((int) tk.getScreenSize().getHeight());

		// Establish full screen size
		mainPanel = new JPanel();
		mainPanel.setPreferredSize(new Dimension(xSize, ySize));
		mainPanel.setLayout(new BorderLayout());
	}// End setWindowSize method

	/**
	 * Holds the table section for servers, which be null if not exists
	 * 
	 * @param sec
	 *            - the server section from GUI
	 */
	public static void setSections(ArrayList<Integer> sec) {
		section = new ArrayList<Integer>();
		section = sec;
	}// end setSections

	/**
	 * Passes the server section back to GUI for setup to keep server section
	 * choices
	 * 
	 * @return - an ArrayList<Integer>
	 */
	public static ArrayList<Integer> getSection() {
		return section;
	}

}// End of Class
